﻿using System;
using System.Globalization;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using eLearning.Model;
using eLearning.Util;
using Microsoft.Devices;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;

namespace eLearning.MahasiswaView
{
    public partial class QuestionPage : PhoneApplicationPage
    {
        private Quiz quiz;
        private QuestionList listSoal;
        private int nomorSoal;
        private double waktuQuiz;
        private bool finish;
        private DispatcherTimer timer;
        private DateTime serverTime;

        public QuestionPage()
        {
            InitializeComponent();
            GetServerTime();
            this.Loaded += new RoutedEventHandler(DataContextPage_Loaded);            
        }

        private void DataContextPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (PhoneApplicationService.Current.State.ContainsKey(Config.QUIZ))
            {
                quiz = (Quiz)PhoneApplicationService.Current.State[Config.QUIZ];
            }

            if (quiz != null)
            {
                startTimerCountDown();
                LoadQuestionList();
            }
        }

        private void GetServerTime()
        {
            string url = string.Format("{0}&{1}", Config.Instance.COMMON_SERVICE_URL() + "?action=time", Guid.NewGuid().ToString());

            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient webClient = new WebClient();
            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(getTime_DownloadStringCompleted);
            try
            {
                webClient.DownloadStringAsync(uri);
            }
            catch (Exception)
            {
                serverTime = DateTime.Now;
            }
        }

        private void getTime_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                string result = e.Result;
                serverTime = DateTime.Parse(result);
            }
            catch (Exception ex)
            {
                serverTime = DateTime.Now;
            }
        }

        private void startTimerCountDown()
        {
            if (timer == null)
            {
                double divTime = quiz.Selesai.Value.Subtract(serverTime).TotalMinutes;
                waktuQuiz = divTime * 60;
                timer = new DispatcherTimer();
                timer.Interval = new TimeSpan(0, 0, 0, 1);
                timer.Tick += new EventHandler(timer_Tick);
            }
            timer.Start();            
        }

        private void stopTimerCountDown(bool isBack)
        {
            if (timer != null)
            {
                timer.Stop();
                pivotQuestion.IsEnabled = false;
                if(!isBack)
                    pivotSoal.Header = "Selesai...";
                else
                    pivotSoal.Header = "Di batalkan...";
                ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = false;
                finish = true;
            }
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            TimeSpan timeSpan = TimeSpan.FromSeconds(waktuQuiz);
            pivotSoal.Header = "Waktu : " + String.Format(CultureInfo.CurrentCulture, "{0:00}:{1:00}", timeSpan.Minutes, timeSpan.Seconds);

            if (timeSpan.TotalSeconds <= 60)
            {
                if (timeSpan.TotalSeconds % 2 == 0)
                {
                    pivotSoal.Header = "Hampir Habis!!!";
                    VibrateController vibrate = VibrateController.Default;
                    vibrate.Start(TimeSpan.FromMilliseconds(1000));
                }
            }

            if (waktuQuiz > 0)
            {
                waktuQuiz--;
            }
            else
            {
                pivotSoal.Header = "Waktu Habis!!!";
                stopTimerCountDown(false);
                MessageBox.Show("Waktu Habis.\nSemua jawaban akan di simpan, dan Quis di tutup!");
                SaveAnsweredQuiz();                
            }
        }

        private void LoadQuestionList()
        {
            string url = string.Format("{0}&{1}", Config.Instance.QUESTION_SERVICE_URL() + Config.VIEW_ACTION_KEY + "Mhs", Guid.NewGuid().ToString());
            string json = JsonConvert.SerializeObject(quiz);

            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient webClient = new WebClient();

            webClient.Encoding = Encoding.UTF8;
            webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
            webClient.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(listQuestion_UploadStringCompleted);
            try
            {
                webClient.UploadStringAsync(uri, "POST", json);
            }
            catch (Exception) { }
        }

        private void listQuestion_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                int noUrut = 0;
                listQuestion.Items.Clear();
                listSoal = new QuestionList();
                QuestionList list = JsonConvert.DeserializeObject<QuestionList>(e.Result);
                foreach (Question ques in list)
                {
                    ques.NoUrut = Convert.ToString((noUrut + 1) + ".");
                    listQuestion.Items.Add(ques);
                    listSoal.Add(ques);
                    noUrut++;
                    if (noUrut == quiz.Jumlah)
                        break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void SaveQuizMhs(NilaiQuiz data)
        {
            string json = null, url = null;

            url = Config.Instance.QUIZ_SERVICE_URL() + "?action=saveQuizMhs"; //simpan nilai
            json = JsonConvert.SerializeObject(data);
            
            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient client = new WebClient();

            client.Encoding = Encoding.UTF8;
            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            client.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            client.UploadStringCompleted += new UploadStringCompletedEventHandler(saveChange_UploadStringCompleted);

            try
            {
                client.UploadStringAsync(uri, "POST", json);
            }
            catch (Exception) { }
        }

        private void saveChange_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                MessageBox.Show("Message : " + e.Result);

                if (e.Result.Contains("Success"))
                    LoadQuestionList();
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }

        private void listQuiz_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                nomorSoal = (sender as ListBox).SelectedIndex;
                ShowDetailQuestion(nomorSoal);
                ((ListBox)sender).SelectedIndex = -1;
            }
        }

        private void ShowDetailQuestion(int nomorSoal)
        {
            textBlockNoUrut.Text = "Soal Nomor " + listSoal[nomorSoal].NoUrut.Replace(".", "") + " :";
            textBoxPertanyaan.Text = listSoal[nomorSoal].Pertanyaan;
            textBoxPilihanA.Text = listSoal[nomorSoal].PilihanA;
            textBoxPilihanB.Text = listSoal[nomorSoal].PilihanB;
            textBoxPilihanC.Text = listSoal[nomorSoal].PilihanC;
            textBoxPilihanD.Text = listSoal[nomorSoal].PilihanD;
            setSelectedJawaban(listSoal[nomorSoal].DiJawab);

            pivotQuestion.SelectedIndex = 1;
        }

        private void saveButton_Click(object sender, System.EventArgs e)
        {
            if (MessageBox.Show("Simpan dan tutup Quiz?", "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                if (isAnsweredAll())
                {
                    SaveAnsweredQuiz();
                    stopTimerCountDown(false);
                }
                else
                {
                    if (MessageBox.Show("Lanjutkan untuk menyimpan?", "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                    {
                        SaveAnsweredQuiz();
                        stopTimerCountDown(false);
                    }
                }
            }
        }

        private char calculateNilai()
        {
            double benar = 0, nilai = 0;
            foreach (Question soal in listSoal)
            {
                if (soal.DiJawab == soal.Jawaban)
                    benar += 1;
            }
            nilai = benar / quiz.Jumlah * 100;
            if (nilai >= 80)
                return 'A';
            else if (nilai >= 70 && nilai < 80)
                return 'B';
            else if (nilai >= 50 && nilai < 70)
                return 'C';
            else if (nilai >= 50 && nilai < 70)
                return 'D';
            return 'E';
        }

        private Jawaban getSelectedJawaban()
        {
            if (radioButtonA.IsChecked.Value)
                return Jawaban.A;
            else if (radioButtonB.IsChecked.Value)
                return Jawaban.B;
            else if (radioButtonC.IsChecked.Value)
                return Jawaban.C;
            else if (radioButtonD.IsChecked.Value)
                return Jawaban.D;
            else
                return Jawaban.None;
        }

        private void setSelectedJawaban(Jawaban jawaban)
        {
            if (jawaban == Jawaban.A)
                radioButtonA.IsChecked = true;
            else if (jawaban == Jawaban.B)
                radioButtonB.IsChecked = true;
            else if (jawaban == Jawaban.C)
                radioButtonC.IsChecked = true;
            else if (jawaban == Jawaban.D)
                radioButtonD.IsChecked = true;
            else
            {
                radioButtonA.IsChecked = false;
                radioButtonB.IsChecked = false;
                radioButtonC.IsChecked = false;
                radioButtonD.IsChecked = false;
            }
        }

        private bool isAnsweredAll()
        {
            bool diJawab = true;
            for (int i = 0; i < listSoal.Count; i++ )
            {
                Question soal = listSoal[i];
                if (soal.DiJawab == Jawaban.None)
                {
                    diJawab = false;
                    MessageBox.Show("Soal nomor " + soal.NoUrut + " belum di jawab!");
                    ShowDetailQuestion(i);

                    break;
                }
            }
            return diJawab;
        }

        private void backButton_Click(object sender, EventArgs e)
        {
            ConfirmBack();
        }

        private void pivotQuestion_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (pivotQuestion.SelectedIndex != 0)
                ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = false;
            else
                ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = true;
        }

        private void SaveAnsweredQuiz()
        {
            NilaiQuiz nilai = new NilaiQuiz();
            nilai.Nilai = calculateNilai();
            nilai.Quis = quiz;
            nilai.Mhs = (Mahasiswa)SavedUser.Instance.User.ConvertUser();

            SaveQuizMhs(nilai);
        }

        private void ConfirmBack()
        {
            if (pivotQuestion.SelectedIndex == 1 && nomorSoal >= 0)
            {
                listSoal[nomorSoal].DiJawab = getSelectedJawaban();
                pivotQuestion.SelectedIndex = 0;
            }
            else
            {
                if (finish)
                {
                    NavigationService.GoBack();
                }
                else
                {
                    if (MessageBox.Show("Simpan dan tutup Quiz?", "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                    {
                        if (isAnsweredAll())
                        {
                            SaveAnsweredQuiz();
                            stopTimerCountDown(false);
                        }
                        else
                        {
                            if (MessageBox.Show("Lanjutkan untuk menyimpan?", "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                            {
                                SaveAnsweredQuiz();
                                stopTimerCountDown(false);
                            }
                        }
                        NavigationService.GoBack();
                    }
                }
            }
        }

        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (pivotQuestion.SelectedIndex == 1 && nomorSoal >= 0)
            {
                listSoal[nomorSoal].DiJawab = getSelectedJawaban();
                pivotQuestion.SelectedIndex = 0;
                e.Cancel = true;
            }
            else
            {
                if (finish)
                {
                    e.Cancel = false;
                }
                else
                {
                    if (MessageBox.Show("Simpan dan tutup Quiz?", "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                    {
                        if (isAnsweredAll())
                        {
                            SaveAnsweredQuiz();
                            stopTimerCountDown(false);
                            e.Cancel = false;
                        }
                        else
                        {
                            if (MessageBox.Show("Lanjutkan untuk menyimpan?", "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                            {
                                SaveAnsweredQuiz();
                                stopTimerCountDown(false);
                                e.Cancel = false;
                            }
                            else
                            {
                                e.Cancel = true;
                            }                    
                        }
                    }
                    else
                    {
                        e.Cancel = true;
                    }                    
                }
            }
        }
    
    }
}